﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Management;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using PIM_ATE.Mods;
using System.Runtime.Serialization.Formatters.Binary;

namespace PIM_ATE
{
    class PIMFunction
    {
        public static string GetCpuID()
        {
            try
            {
                string cpuInfo = "";
                ManagementClass mc = new ManagementClass("Win32_Processor");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
                }
                moc = null;
                mc = null;
                return cpuInfo;
            }
            catch
            {
                return "unknow";
            }
        }

        public static string GetMacAddress()
        {
            try
            {
                string mac = "";
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        mac = mo["MacAddress"].ToString();
                        break;
                    }
                }
                moc = null;
                mc = null;
                return mac;
            }
            catch
            {
                return "unknow";
            }
        }

        public static string GetIPAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }
            return "";
        }

        #region mods
        public static string getPIMTestType(ClsDataConfig config)
        {
            string strType = "";
            if (config.IsSweepTest && !config.IsKnock)
                strType = "扫频";
            else if(!config.IsSweepTest && !config.IsKnock)
                strType = "点频";
            else if (config.IsSweepTest && config.IsKnock)
                strType = "扫频敲击";
            else if (!config.IsSweepTest && config.IsKnock)
                strType = "点频敲击";
            return strType;
        }

        public static string getPIMTestBandInfo(ClsDataConfig config)
        {
            string strInfo = "";
            if (!config.IsSweepTest)
            {
                strInfo += "F1=" + config.F1Freq + "   ";
                strInfo += "F2=" + config.F2Freq + "   ";
                strInfo += "FPIM=" + config.PIMFreq;
            }
            else
            {
                strInfo += "TX(" + config.TXL + "-" + config.TXH + ")   ";
                strInfo += "RX(" + config.RXL + "-" + config.RXH + ")   ";
                strInfo += "RXSTEP=" + config.RXStep;
            }
            return strInfo;
        }

        public static double getCheckValue(double real, double spec, double A)
        {
            //double k = Math.Pow(2, 1 / Math.Abs(A));
            //double value = real + (spec - A) / Math.Pow(k, Math.Abs(real - A));
            //return value;

            double k = Math.Pow(2, 1 / Math.Abs(A));
            double value = real + A / Math.Pow(k, Math.Abs(real - (spec - A))); ;
            return Math.Round(value, 1);
        }

        public static void formateSpec(string strSpec, ref double f1, ref double f2)
        {
            string[] s = strSpec.Split(',');
            if (s.Length == 2)
            {
                char c1, c2;
                c1 = s[0][0];
                c2 = s[1][s[1].Length - 1];

                s[0] = s[0].Substring(1);
                s[1] = s[1].Substring(0, s[1].Length - 1);
                double.TryParse(s[0], out f1);
                double.TryParse(s[1], out f2);

                if (s[0].ToUpper() == "-INF")
                    f1 = double.MinValue;
                else if (s[0].ToUpper() == "+INF")
                    f1 = double.MaxValue;

                if (s[1].ToUpper() == "-INF")
                    f2 = double.MinValue;
                else if (s[1].ToUpper() == "+INF")
                    f2 = double.MaxValue;

                if (f2 < f1)
                {
                    double temp = f1;
                    f1 = f2;
                    f2 = temp;
                }
            }
        }

        public static bool compareSpec(double value, string strSpec)
        {
            double spec;
            if (double.TryParse(strSpec, out spec))
            {
                return value <= spec;
            }

            string[] s = strSpec.Split(',');
            if (s.Length == 2)
            {
                char c1, c2;
                double f1, f2;
                c1 = s[0][0];
                c2 = s[1][s[1].Length - 1];

                s[0] = s[0].Substring(1);
                s[1] = s[1].Substring(0, s[1].Length - 1);
                double.TryParse(s[0], out f1);
                double.TryParse(s[1], out f2);

                if (s[0].ToUpper() == "-INF")
                    f1 = double.MinValue;
                else if (s[0].ToUpper() == "+INF")
                    f1 = double.MaxValue;

                if (s[1].ToUpper() == "-INF")
                    f2 = double.MinValue;
                else if (s[1].ToUpper() == "+INF")
                    f2 = double.MaxValue;

                if (f2 < f1)
                {
                    double temp = f1;
                    f1 = f2;
                    f2 = temp;
                }

                if (c1 == '[' && c2 == ']')
                {
                    return value >= f1 && value <= f2;
                }
                else if (c1 == '(' && c2 == ')')
                {
                    return value > f1 && value < f2;
                }
                else if (c1 == '[' && c2 == ')')
                {
                    return value >= f1 && value < f2;
                }
                else if (c1 == '(' && c2 == ']')
                {
                    return value > f1 && value <= f2;
                }
            }
            return false;
        }

        #endregion

        #region PIM

        public static float getMax(List<JcPIMDataResults> results, out int index)
        {
            float max = float.MinValue;
            index = -1;
            for (int i = 0; i < results.Count; i++)
            {
                if (results[i].Im_V > max)
                {
                    max = results[i].Im_V;
                    index = i;
                }
            }
            return max;
        }

        public static float getMax(JcPIMDataResults[] results, out int index)
        {
            float max = float.MinValue;
            index = -1;
            for (int i = 0; i < results.Length; i++)
            {
                if (results[i].Im_V > max)
                {
                    max = results[i].Im_V;
                    index = i;
                }
            }
            return max;
        }

        public static float getMax(List<JcPIMDataResults> results)
        {
            float max = float.MinValue;
            for (int i = 0; i < results.Count; i++)
            {
                if (results[i].Im_V > max)
                {
                    max = results[i].Im_V;
                }
            }
            return max;
        }

        public static float getMax(JcPIMDataResults[] results)
        {
            float max = float.MinValue;
            for (int i = 0; i < results.Length; i++)
            {
                if (results[i].Im_V > max)
                {
                    max = results[i].Im_V;
                }
            }
            return max;
        }

        public static string GetValueSection(float value)
        {
            value = Math.Abs(value);
            if (value == 0)
            {
                return "";
            }
            else if (value < 90)
            {
                return "90以下";
            }
            else if (value < 100 && value >= 90)
            {
                return "90-100";
            }
            else if (value < 107 && value >= 100)
            {
                return "100-107";
            }
            else if (value < 110 && value >= 107)
            {
                return "107-110";
            }
            else
            {
                return "110以上";
            }
        }

        public static string GetPIMShiftTime(DateTime time)
        {
            var t1 = new TimeSpan(7, 50, 00);
            var t2 = new TimeSpan(20, 30, 00);

            if (time.TimeOfDay >= t1 && time.TimeOfDay <= t2)
            {
                return "白班";
            }
            else
            {
                return "晚班";
            }
        }

        #endregion

        #region ELEC

        public static float FreqToHz(string sFreq)
        {//例如 562.8MHz -》 5628000
            sFreq = sFreq.Trim().ToUpper();

            if (sFreq.IndexOf("GHz".ToUpper()) != -1)
            {
                sFreq = sFreq.ToUpper().Replace("GHZ", "");
                return Convert.ToSingle(sFreq) * 1000000000;
            }
            else if (sFreq.IndexOf("MHz".ToUpper()) != -1)
            {
                sFreq = sFreq.ToUpper().Replace("MHZ", "");
                return Convert.ToSingle(sFreq) * 1000000;
            }
            else if (sFreq.IndexOf("kHz".ToUpper()) != -1)
            {
                sFreq = sFreq.ToUpper().Replace("KHZ", "");
                return Convert.ToSingle(sFreq) * 1000;
            }
            else if (sFreq.IndexOf("Hz".ToUpper()) != -1)
            {
                sFreq = sFreq.ToUpper().Replace("HZ", "");
                return Convert.ToSingle(sFreq) * 1;
            }
            else
            {//没有单位的暂时用MHZ处理
                sFreq = sFreq.ToUpper().Trim();
                return Convert.ToSingle(sFreq) * 1000000;
            }
        }

        public static string GetShowValue(string valType, float f1, float f2, out float fVal1, out float fVal2)
        {
            fVal1 = 0;
            fVal2 = 0;
            string[] arrExt = valType.Split('#');
            float fExtValue = 0;
            if (arrExt.Length < 1)
                return "";
            valType = arrExt[0];
            if (arrExt.Length > 1)
                fExtValue = Convert.ToSingle(arrExt[1]);
            switch (valType)
            {
                case "最大值的绝对值":
                    fVal1 = (float)Math.Round(Math.Abs(f1) + fExtValue, 2);
                    return fVal1.ToString();

                case "最小值的绝对值":
                    fVal1 = (float)Math.Round(Math.Abs(f2) + fExtValue, 2);
                    return fVal1.ToString();

                case "最大值-最小值":
                    fVal1 = (float)Math.Round(Math.Abs(f1 - f2) + fExtValue, 2);
                    return fVal1.ToString();

                case "最大值和最小值":
                    fVal1 = (float)Math.Round(Math.Abs(f1) + fExtValue, 2);
                    fVal2 = (float)Math.Round(Math.Abs(f2) + fExtValue, 2);
                    return fVal1.ToString() + ", " + fVal2.ToString();

                case "定点值":
                    fVal1 = (float)Math.Round(Math.Abs(f1) + fExtValue, 2);
                    return fVal1.ToString();

                default:
                    return "";
            }

        }

        public static bool GetResult(string factor, float val, float val2)
        {
            string header;
            float fac;
            float fac2;

            //header = factor.Substring(0, 2);

            Regex rx = new Regex(@"(\d+)\.(\d+)|(\d+)");
            MatchCollection ms = rx.Matches(factor);
            if (ms.Count >= 2)
            {
                fac = Convert.ToSingle(ms[0].Value);
                fac2 = Convert.ToSingle(ms[1].Value);
            }
            else
            {
                fac = Convert.ToSingle(ms[0].Value);
                fac2 = 999;
            }

            rx = new Regex(@"(\<)|(\>)|(\=)|(\±)|(\≤)|(\≥)|(\%)");
            ms = rx.Matches(factor);
            if (ms.Count >= 2)
            {
                header = ms[0].Value + ms[1].Value;
            }
            else if (ms.Count == 1)
            {
                header = ms[0].Value;
            }
            else
            {
                MessageBox.Show("内控指标不合法: " + factor);
                return false;
            }

            //Regex rx2 = new Regex(@"([A-Za-z]+)");
            //MatchCollection ms2 = rx2.Matches(factor);
            //if (ms2.Count != 0)
            //    unit = ms2[0].Value;
            //else
            //    unit = null;

            if (header == "±")
            {
                if (val2 != 0)
                {//两个值
                    if (val <= (fac + fac2) && val >= (fac - fac2) && val2 <= (fac + fac2) && val2 >= (fac - fac2))
                        return true;
                    else
                        return false;
                }
                else
                { //一个值
                    if (val <= (fac + fac2) && val >= (fac - fac2))
                        return true;
                    else
                        return false;
                }
            }
            else if (header == "%")
            {
                if (val <= (fac + fac2) && val >= (fac - fac2))
                    return true;
                else
                    return false;
            }
            else if (header == "<=" || header == "≤")
            {
                if (val <= fac)
                    return true;
                else
                    return false;
            }
            else if (header == ">=" || header == "≥")
            {
                if (val >= fac)
                    return true;
                else
                    return false;
            }
            else if (header == ">")
            {
                if (val > fac)
                    return true;
                else
                    return false;
            }
            else if (header == "<")
            {
                if (val < fac)
                    return true;
                else
                    return false;
            }
            return false;
        }

        #endregion

        public static string getTime(string server)
        {
            string sql = "SELECT CONVERT(varchar(100),GETDATE(),25)";
            //if (server == "MOD")
            //{
            //    sql = "SELECT CONVERT(varchar(100),GETDATE(),20)";
            //}
            return (string)MicroDBHelper.ExecuteScalar(sql, null, server);
        }

        public static bool getBoolean(string value)
        {
            if (value.ToLower() == "是" || value.ToLower() == "yes" || 
                value.ToLower() == "true"  || value.ToLower() == "1")
                return true;
            else
                return false;
        }

        public static string getColNameString(List<string> cols, int start = 0)
        {
            string[] names = cols.ToArray();
            string sColNames = "";
            for (int i = start; i < names.Length; i++)
            {
                if (i != names.Length - 1)
                    sColNames += "[" + names[i] + "],";
                else
                    sColNames += "[" + names[i] + "]";
            }
            return sColNames;
        }
    }

    /// <summary>
    /// 通用的深复制方法
    /// </summary>
    /// <typeparam name="T"></typeparam>
    [Serializable]
    public class BaseClone<T>
    {
        public virtual T Clone()
        {
            MemoryStream memoryStream = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(memoryStream, this);
            memoryStream.Position = 0;
            return (T)formatter.Deserialize(memoryStream);

        }
    }

    public class Insert_Standard_ErrorLog
    {
        public static void Insert(string log)
        {
            try
            {
                string file_path = Application.StartupPath + "\\LOG";
                if (!Directory.Exists(file_path))
                {
                    Directory.CreateDirectory(file_path);
                }

                string file_name = file_path + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                FileStream fs = new FileStream(file_name, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine("====>" + DateTime.Now.ToString() + ": " + log);
                sw.Close();
                fs.Close();
            }
            catch (Exception) { }
        }

        public static void WriteException(Exception ex)
        {
            try
            {
                FileStream fs = new FileStream(Application.StartupPath + "\\Error.txt",
                               FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss    ") + ex.Message);
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss    ") + ex.StackTrace);
                //sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss    ") + ex.Source);
                sw.Close();
                fs.Close();

            }
            catch (Exception) { }
        }
    }


}
